/*
 * (c) Copyright 2002 HMS.
 * All Rights Reserved.
 */
package com.bff.slimserver.musicjukebox.ui.components;

import com.bff.slimserver.music.SongTransferable;
import com.bff.bjj.ui.component.ColorProperties;
import com.bff.slimserver.musicjukebox.lib.SongTableModel;
import com.bff.slimserver.utils.TableSorter;
import java.awt.Dimension;
import java.awt.datatransfer.Transferable;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.TransferHandler;
import javax.swing.table.TableModel;

/**
 * @author bill
 */
public class SongTable extends JTable {

    private TableSorter tableSorter;

    public SongTable() {
        super();

        setTransferHandler(new FromTransferHandler());
        setDragEnabled(true);

        setDefaultRenderer(Object.class, new SongCellRenderer());
        setGridColor(ColorProperties.TABLE_HEADER_BACKGROUND);
        setIntercellSpacing(new Dimension(1, 1));
        setShowGrid(false);
        setShowVerticalLines(true);
        setBorder(null);
    }

    @Override
    public void setModel(TableModel tableModel) {

        if (tableModel instanceof TableSorter) {
            setTableSorter((TableSorter) tableModel);
        } else {
            setTableSorter(new TableSorter(tableModel));

            if (tableModel instanceof SongTableModel) {
                setModel((SongTableModel) tableModel);
            }
        }
        super.setModel(getTableSorter());
    }

    public TableSorter getTableSorter() {
        return tableSorter;
    }

    public void setTableSorter(TableSorter tableSorter) {
        this.tableSorter = tableSorter;
    }

    class FromTransferHandler extends TransferHandler {

        public int getSourceActions(JComponent comp) {
            return MOVE;
        }

        public Transferable createTransferable(JComponent comp) {
            int index = getSelectedRow();
            if (index < 0 || index >= getRowCount()) {
                return null;
            }

            SongTableModel model = (SongTableModel) (getTableSorter().getTableModel());
            return new SongTransferable(model.getSong(getTableSorter().modelIndex(index)));
        }

        public void exportDone(JComponent comp, Transferable trans, int action) {
            return;
        }
    }
}
